/** This class represents the client listener thread 
 *  @author Copyright (c) 2004-2007 by chrmac@gmx.de */

package info.chrm.jtalker;

import java.io.*;
import java.net.*;
import java.util.*;
import info.chrm.helper.*;

public class JTalkerClientThread extends Thread {
    private BufferedReader in;
    private JTalkerClient theClient;
    private String lastPackage;
    boolean hasNewPackage = false;
    boolean stopNow = false;
    //ArrayList packQueue = new ArrayList();

    public JTalkerClientThread(JTalkerClient _theClient, BufferedReader _in) {
        this.theClient = _theClient;
        this.in = _in;
    }

    public String getLastPackage() {        
        return this.lastPackage;
    }

    public void terminate() {
        this.stopNow = true;
    }

    public void run() {

        try { 
            while((this.lastPackage = in.readLine()) != null) {
                System.out.println("[recv]: " + this.lastPackage);

                if(stopNow)
                    return;

                try {
                        if(!this.theClient.myProtocol.processServerPackage(this.lastPackage))
                            System.err.println("*** Thread: Faulty package recieved: " + this.lastPackage);
                } catch (Exception _e) { 
                        System.err.println("*** Thread: Exception occured while parsing server package: " + _e.getMessage());
                } 
            }
        } catch (Exception _e) { 
            System.err.println("*** Thread: Main-Loop-Error: " + _e.getMessage());
        } 

        // Notify end of thread
        System.err.println("*** Thread: END: ");
        
        if(!this.stopNow)
            this.theClient.mainLoopError();
    }
}
